const app = angular.module("myApp",['ui.bootstrap']);

const interval_span = 30000;

app.controller("diagnosisController",['$scope','$window','$interval',function($scope,$window,$interval){
    $scope.toJSON = function (val) {
        return toJSON(val);
    };

    $scope.showUnknown = false;
    $scope.timerState = 1;
    $scope.faultCheck = {};
    $scope.faultMatched=[];

    $scope.inCheckList = function (signal) {
        return $scope.faultMatched.filter(fault=>fault!=null && fault.checked).some(fault=>fault.signalPorts.some(channel=>channel.id==signal.portId));
    };

    $scope.withUnknown = function (fault) {
        return fault!=null && (fault.isMatched || $scope.showUnknown && fault.isUnknown);
    };

    let timestamp = new Date().getTime();
    function fetchKG() {
        if($scope.timerState==0){
            return;
        }
        timestamp += interval_span;
        $.get('http://'+window.location.hostname+":"+window.basePort+'/rest/work/last/kg/match/'+timestamp,function (data) {
            // data = data.map(f=>{
            //     f.id = f.faultId;
            //     return f;
            // });
            // let gIds = data.map(f=>f.id);
            $scope.matchedResult = data;
            // $scope.faults = FaultNode.faults.filter(f=>gIds.some(id=>id==f.id));
            let lastCheck = {};
            $scope.faultMatched.forEach(f=>{
                lastCheck[f.id] = f.checked;
            });
            $scope.faultMatched = data.map(f=>{
                f.checked = lastCheck[f.id] || false;
                return f;
            });
            $scope.$apply();
        });
    }

    function fetchSignal() {
        if($scope.timerState==0){
            return;
        }
        $.get('http://'+window.location.hostname+":"+window.basePort+'/rest/work/last/signal/'+timestamp,function (data) {
            $scope.signals = data;
            // $scope.signals2 = _.flatMap($scope.signals,obj=>{
            //     let val = obj;
            //     if(obj.value && obj.value instanceof Array){
            //         return obj.value.map((vl,id)=>{
            //             return {
            //                 componentName:val.component.name+(id+1),
            //                 featureType:val.featureType,
            //                 value:vl
            //             }
            //         });
            //     }else {
            //         return [
            //             {
            //                 componentName:val.component.name,
            //                 featureType:val.featureType,
            //                 value:val.value
            //             }
            //         ];
            //     }
            // });
            // console.info($scope.signals2);
            $scope.$apply();
        });
    }

    fetchKG();
    fetchSignal();

    $interval(fetchKG,interval_span);
    $interval(fetchSignal,interval_span);

    function showToReport(faultId,filename,title) {
        let result = $scope.matchedResult.filter(res=>res.id==faultId)[0];
        let matchedNodes,unknownNodes,channels;
        if(result!=null)
            matchedNodes = angular.toJson(result["matched"],false);
        else
            matchedNodes = "[]";

        if(result!=null)
            unknownNodes = angular.toJson(result["unknown"],false);
        else
            unknownNodes = "[]";

        if(result!=null){
            channels = angular.toJson(result["signalPorts"].map(ch=>{
                let value = _.find($scope.signals,port=>port.portId==ch.id).value;
                ch.value = value;
                return ch;
            }),false);
        }else {
            channels = "[]";
        }

        let jumpTo = `${filename}?faultId=${faultId}&matchedNodes=${encodeURI(matchedNodes)}&unknownNodes=${encodeURI(unknownNodes)}&timestamp=${timestamp}&last_timestamp=${result.last_timestamp}&reportId=${result.reportId}&channels=${encodeURI(channels)}`;
        if(isInFrame()){
            pushUrl(`../fault/${jumpTo}`,title);
        }else{
            $window.open(jumpTo);
        }
    }

    $scope.showFaultReport = function (faultId) {
        showToReport(faultId,"report.html","诊断报告");
    };

    $scope.showFaultTree = function (faultId) {
        showToReport(faultId,"FaultExplain.html","诊断解释");
    };

    $scope.jumpToHuman = function (fid) {
        alert("转到人工！！！");
    };

    $scope.toLatest = function () {
        timestamp = new Date().getTime();
    };
}]);

const toJSON = function (obj) {
    let cache = [];
    return JSON.stringify(obj, function(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                return;
            }
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
};

const isInFrame = function () {
  return localStorage.getItem("useInFrame")=="true";
};

const pushUrl = function (url,title) {
    let stackStr = localStorage.getItem("tabStack") || "[]";
    let stack = JSON.parse(stackStr);
    stack.push({
        url:url,
        title:title
    });
    stackStr = JSON.stringify(stack);
    localStorage.setItem("tabStack",stackStr);
};


app.filter('startX', [function() {
    return function(array,size) {
        if(array.length<=size)
            return array.map(x=>x.toFixed(2)).join(",");
        return array.slice(0,2).map(x=>x.toFixed(2)).join(",")+"等"+array.length+"项";
    };
}]);